
import store from '@/store'
import { getToken } from '@/utils/auth'
import { notifiyError } from '@/utils/public'

// 协议列表
var Protocol = {
  PAGE_HEALTH: 'PAGE_HEALTH',
  PAGE_PRODUCE: 'PAGE_PRODUCE',
  PAGE_COMMAND: 'PAGE_COMMAND'
}

/**
 * 系统消息对象
 */
export default function Socket(name) {
  var thiz = this

  thiz.url = `${process.env.VUE_APP_WEBSOCKET_API}/itps/${name || 'repair'}/websocket/${store.state.app.userInfo.id}?access_token=${getToken()}`
  thiz.errorTimer = null
  thiz.events = {
    'onopenError': undefined,
    'onopen': undefined,
    'onclose': undefined,
    'PAGE_HEALTH': undefined,
    'PAGE_PRODUCE': undefined,
    'PAGE_COMMAND': undefined
  }
  /**
     * 触发指定事件
     * @param {Object} eventName 事件名称(此参数不能省略)
     */
  thiz.fireEvent = function(eventName) {
    var fun = this.events[eventName]
    if (fun) {
      return fun.apply(this, Array.prototype.slice.call(arguments, 1))
    }
  }
  /**
     * 添加事件监听
     * @param {Object} event 监听事件名称
     * @param {Object} callback 回调函数
     */
  thiz.addEventListener = function(eventName, callback) {
    this.events[eventName] = callback
  }
  /**
     * 发送信息
     * @message 消息对象
     */
  thiz.sendMessage = function(message) {
    this.ws.send(message)
  }
  /**
     * 连接服务器通讯
     */
  thiz.open = function() {
    let ws
    try {
      if ('WebSocket' in window) {
        ws = new WebSocket(thiz.url)
      } else if ('MozWebSocket' in window) {
        ws = new MozWebSocket(thiz.url)
      } else {
        notifiyError('当前浏览器版本过低,请使用Internet Explorer10+,Chrome4+,Firefox4+浏览器！')
        return
      }
    } catch (e) {
      thiz.fireEvent('onopenError', e)
    }

    clearTimeout(thiz.errorTimer)

    // 定义Open事件处理函数
    ws.onopen = function(evnt) {
      const self = this
      if (thiz.events.onopen) {
        thiz.events.onopen(self)
      }
      console.info('连接成功')
    }
    // 定义Message事件处理函数(收取服务端消息并处理)
    ws.onmessage = function(evt) {
      const msg = JSON.parse(evt.data)
      console.log(msg)
      switch (msg.topic) {
        case Protocol.PAGE_HEALTH:
          thiz.fireEvent(Protocol.PAGE_HEALTH, msg)
          break
        case Protocol.PAGE_COMMAND:
          thiz.fireEvent(Protocol.PAGE_COMMAND, msg)
          break
        case Protocol.PAGE_PRODUCE:
          thiz.fireEvent(Protocol.PAGE_PRODUCE, msg)
          break
      }
    }
    // 定义error事件
    ws.onerror = function(evnt) {
      notifiyError('连接服务器异常,10秒后自动重新连接服务器...')
      thiz.errorTimer = window.setTimeout(function() {
        // window.location.reload(true)
        thiz.open()
      }, 10000)
    }
    // 定义Close事件处理函数
    // ws.onclose = thiz.events.onclose ? thiz.events.onclose : function(evnt) {
    //   notifiyError('与服务器连接中断,10秒后自动重新连接服务器...')
    //   window.setTimeout(function() {
    //     window.location.reload(true)
    //   }, 10000)
    // }
    thiz.ws = ws
  }
}
